package com.qa.common.utils;

import org.springframework.beans.BeanUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 普通工具类
 */
public class CommonUtil {

    /**
     * 根据当前时间生成id："yyMMddHHmmss"
     *
     * @return 生成的id
     */
    public static String initIdByNowTime() {
        DateTimeFormatter formatterForId = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        LocalDateTime now = LocalDateTime.now();
        return now.format(formatterForId).substring(2);
    }

    /**
     * 获取当前时间
     *
     * @return 生成的日期时间
     */
    public static String getNowTime() {
        DateTimeFormatter formatterForCreateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime now = LocalDateTime.now();
        return now.format(formatterForCreateTime);
    }

    /**
     * 通过反射创建实例
     *
     * @param targetClass 目标类
     * @param <T>         泛型
     * @return 实例
     */
    public static <T> T newInstance(Class<T> targetClass) {
        try {
            return targetClass.getConstructor().newInstance();
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException("Failed to instantiate " + targetClass.getName(), e);
        }
    }

    /**
     * 拷贝List
     *
     * @param sourceList  源
     * @param targetClass 目标
     * @param <S>         源类型
     * @param <T>         目标类型
     * @return 目标
     */
    public static <S, T> List<T> copyList(List<S> sourceList, Class<T> targetClass) {
        List<T> targetList = new ArrayList<>();
        System.out.println("targetClass=" + targetClass);
        for (S s : sourceList) {
            T t = newInstance(targetClass);
            BeanUtils.copyProperties(s, t);
            targetList.add(t);
        }
        return targetList;
    }
}
